package com.zx.idc.backend.gui.api.management.infosecurity.activeresources.base;

import com.zx.idc.backend.gui.api.management.infosecurity.activeresources.base.pojo.ReportDate;
import com.zx.idc.common.lang.ListUtil;
import com.zx.idc.common.spring.SpringConfigUtil;
import com.zx.idc.common.util.FileUtils;
import com.zx.idc.common.util.DateFormatterStringEnum;
import com.zx.idc.common.util.LocalDateTimeFormatUtil;
import com.zx.idc.ds.base.house.entity.BaseHouseInfo;
import com.zx.idc.ds.base.house.service.IBaseHouseInfoService;
import com.zx.idc.ds.base.oper.service.IBaseOperCompanyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static org.apache.commons.io.FileUtils.readLines;

public abstract class BaseActiveResourceService<T> {

    protected final Logger log = LoggerFactory.getLogger(getClass());

    private final String dirKey;

    private static final Charset UTF_8 = Charset.forName("UTF-8");

    private static final String FILE_SUFFIX = ".txt";

    protected BaseActiveResourceService(String dir) {
        this.dirKey = dir;
    }

    @Autowired
    private IBaseHouseInfoService iBaseHouseInfoService;

    @Autowired
    private IBaseOperCompanyService iBaseOperCompanyService;


    /**
     * 获取上报数据
     *
     * @return
     */
    public ReportDate<T> getReportDate() {
        log.debug("{} ：upload start!", dirKey);
        List<String> paths = getPaths();
        log.debug("{} ：get upload paths:{}", dirKey, paths);
        List<T> lists = new ArrayList<>();
        if (ListUtil.isNotEmpty(paths)) {
            for (String path : paths) {
                try {
                    //读出所有内容
                    List<String> strings = readLines(new File(path), UTF_8);
                    String[] split = path.split("/");
                    String houseId = split[split.length - 2];
                    lists.addAll(dataConversion(strings, houseId));
                } catch (IOException e) {
                    log.error("活跃资源上报读出文件错误", e);
                }
            }
        }
        log.debug("{} ：upload done!", dirKey);
        return new ReportDate<T>().setData(lists).setFilePaths(paths);
    }

    /**
     * 获取前一天的当前时间
     *  格式{yyyyMMdd}
     *
     * @return
     */
    private String getYestDayTime() {
        //获取前一天
        return LocalDateTimeFormatUtil.formatLocalDate(
            LocalDate.now().minusDays(1L),
            DateFormatterStringEnum.YYYY_MM_DD
        );
    }

    private List<String> getPaths() {
        String yestDay = getYestDayTime();
        String srcDir = FileUtils.checkDirPathEndSeparator(SpringConfigUtil.get(dirKey));
        //获取idc的所有机房

        String idcId = iBaseOperCompanyService.getIdcId();
        List<BaseHouseInfo> baseHouseInfos = iBaseHouseInfoService.selectList(new BaseHouseInfo().setIdcId(idcId));
        return baseHouseInfos.stream().map(baseHouseInfo ->
            new StringBuilder()
                .append(srcDir)
                .append(baseHouseInfo.getId())
                .append("/")
                .append(yestDay)
                .append(FILE_SUFFIX)
                .toString()
        ).collect(Collectors.toList());

    }

    public abstract List<T> dataConversion(List<String> data, String houseId);
}
